<template>
	<a-form-item-rest>
		<a-select
			v-if="!isEmbed"
			:class="[
				'app-editor-container',
				'app-data-picker-view',
				`app-data-picker-view-${name}`,
			]"
			showSearch
			v-model:value="curValue"
			:disabled="disabled"
			:filterOption="false"
			:mode="multiple ? 'multiple' : 'tag'"
			dropdownClassName="dropdown__embed-view"
			:placeholder="
				placeholder ? placeholder : $t('common.datapickerview.placeholder')
			"
			:open="open"
			:options="items"
			:fieldNames="fieldNames"
			@change="onChange"
			@focus="onFocus"
			@blur="onBlur"
		>
			<template #suffixIcon>
				<span class="app-data-picker-dropdown-select-icon">
					<CloseCircleOutlined
						v-show="curValue"
						class="close-icon suffix-icon"
						@click="clear"
					/>
					<DownOutlined
						v-show="!open"
						@click="switchAppAc"
						class="down-icon suffix-icon"
					/>
					<UpOutlined
						v-show="open"
						@click="switchAppAc"
						class="up-icon suffix-icon"
					/>
					<SearchOutlined v-if="pickUpView" class="" @click="openView" />
					<LinkOutlined v-if="enableLinkView" @click="openLinkView" />
				</span>
			</template>
			<template #dropdownRender>
				<component
					openType="EMBED"
					class="view-container2"
					:is="pickUpView"
					:context="context"
					:viewParams="tempViewParams"
					:name="pickUpView"
					@mousedown="(e: Event) => e.preventDefault()"
					@view-action="handleViewAction"
				/>
			</template>
		</a-select>
		<div v-else class="data-picker-view__embed-view">
			<component
				openType="EMBED"
				class="view-container2"
				:is="pickUpView"
				:context="context"
				:viewParams="tempViewParams"
				:name="pickUpView"
				@view-action="handleViewAction"
			/>
		</div>
	</a-form-item-rest>
</template>

<script setup lang="ts">
import { Ref, ref } from 'vue';
import { FormItemRest } from 'ant-design-vue';
import {
	DownOutlined,
	UpOutlined,
	CloseCircleOutlined,
	SearchOutlined,
	LinkOutlined,
} from '@ant-design/icons-vue';
import {
	deepCopy,
	IParam,
	IEvent,
	IContext,
	isExistAndNotEmpty,
	IViewDetail,
} from '@/core';
import { dataPickerViewProps } from './data-picker-view';
import { handleEditorNavParams, useEditorTypeParams } from '@/hooks/use-editor';
// 数据选择部件，将选择视图直接嵌入在部件中，用于在表单中直接呈现选择数据
// 数据选择部件，将选择视图呈现在下拉option中，用于在其他视图选择数据、，另外为方便快速查看引用的数据，还提供了数据链接功能，可直接打开引用数据的相关视图(单选)
interface EditorEmit {
	(name: 'component-action', value: IEvent<string>): void;
}
const props = defineProps(dataPickerViewProps);
const emit = defineEmits<EditorEmit>();
const compAttrs: IParam = useAttrs();
const enableLinkView = computed(() => {
	return compAttrs.LINKVIEW == 'TRUE';
});

// 类型校验
const {
	validateConfig,
	valueType,
	objectNameField,
	objectValueField,
	objectIdField,
	valueSeparator,
	textSeparator,
} = useEditorTypeParams();
validateConfig();

const fieldNames = {
	label: props.deMajorField,
	value: props.deKeyField,
};
const { navContext, navViewParam } = handleEditorNavParams(props);
const items: Ref<any> = ref([]);
/**
 * 当前值
 */
const curValue = computed(() => {
	let value: any;
	try {
		if (props.value && props.valueItem) {
			const _items: IParam[] = [];
			if (props.multiple) {
				value =
					props.data[props.valueItem].split(
						valueSeparator ? valueSeparator : ','
					) || [];
				if (valueType == 'OBJECTS') {
					(props.value as any[]).forEach((item: any, index: number) => {
						_items.push({
							[props.deMajorField]: item[objectNameField as string],
							[props.deKeyField]: value[index],
						});
					});
				} else if (valueType == 'SIMPLES') {
					(props.value as string[]).forEach((item: string, index: number) => {
						_items.push({
							[props.deMajorField]: item,
							[props.deKeyField]: value[index],
						});
					});
				} else {
					const texts = (props.value as string).split(
						textSeparator ? textSeparator : ','
					);
					texts.forEach((text: string, index: number) => {
						_items.push({
							[props.deMajorField]: text,
							[props.deKeyField]: value[index],
						});
					});
				}
			} else {
				if (valueType == 'OBJECT') {
					value = (props.value as any)[objectNameField as string];
				} else {
					value = props.value;
				}
				_items.push({
					[props.deMajorField]: props.value,
					[props.deKeyField]: props.data[props.valueItem],
				});
			}
			if (_items.length > 0) {
				_items.forEach((_item: IParam) => {
					const index = items.value.findIndex(
						(item: IParam) => item[props.deKeyField] == _item[props.deKeyField]
					);
					if (index == -1) {
						items.value.push(_item);
					}
				});
			}
		}
	} catch (error) {
		console.log(error);
	}
	return value;
});

const tempViewParams = computed(() => {
	const viewParams: any = deepCopy(navViewParam);
	if (props.valueItem && props.value) {
		const valueItem: string[] = props.data[props.valueItem].split(
			valueSeparator ? valueSeparator : ','
		);
		let srfselecteddata: IParam[] = [];
		valueItem.forEach((value: string) => {
			const _item = items.value.find(
				(_item: IParam) => value == _item[props.deKeyField]
			);
			if (_item) {
				srfselecteddata.push({
					srfkey: _item[props.deKeyField],
					srfmajortext: _item[props.deMajorField],
				});
			}
		});
		Object.assign(viewParams, { srfselecteddata });
	}
	return viewParams;
});
const open = ref(false);
/**
 * @description 切换下拉显示
 */
const switchAppAc = () => {
	open.value = !open.value;
};

/**
 * @description 聚焦状态
 */
const onFocus = ($event: any) => {
	open.value = true;
	emit('component-action', {
		name: `${props.name}`,
		action: 'editorFocus',
		data: $event,
	});
};
/**
 * @description 失焦
 */
const onBlur = ($event: any) => {
	emit('component-action', {
		name: `${props.name}`,
		action: 'editorBlur',
		data: $event,
	});
};

/**
 * @description 打开链接视图
 */
const openLinkView = (event: any): void => {
	event.preventDefault();
	event.stopPropagation();
	if (
		!props.data ||
		!props.valueItem ||
		!props.data.hasOwnProperty(props.valueItem)
	) {
		const error = App.ts('common.generic.error', '错误');
		const formdataexception = App.ts(
			'common.datapicker.formdataexception',
			'表单数据异常！'
		);
		const valueitemexception = App.ts(
			'common.datapicker.valueitemexception',
			'值项异常'
		);
		if (!props.data) {
			console.error(error, formdataexception);
		} else {
			console.error(error, valueitemexception);
		}
		return;
	}
	if (!props.linkView) {
		return;
	}
	// 公共参数处理
	let data: any = {
		param: {},
		context: {},
	};
	Object.assign(data.param, navViewParam);
	Object.assign(data.context, navContext);

	// 参数处理
	let _context = data.context;
	let _param = data.param;
	Object.assign(_context, { [props.deKeyField]: props.data[props.valueItem] });

	const view = App.getAppViewConfig()?.[props.linkView];
	App.getOpenViewHelper().openPage(view, _context, _param);
};

// 打开一般视图
const openView = (event: any) => {
	event.preventDefault();
	event.stopPropagation();
	if (props.disabled) {
		return;
	}
	if (!props.pickUpView) {
		return;
	}
	const view = App.getAppViewConfig()?.[props.pickUpView];
	if (!view) {
		return;
	}
	const params: IParam = {};
	//打开视图
	if (
		!Object.is(view.openMode, 'POPOVER') &&
		!Object.is(view.openMode, 'DRAWER')
	) {
		Object.assign(params, { openMode: 'POPUPMODAL' });
	}
	if (Object.is(params.openMode, 'POPUPMODAL')) {
		openPopupModal(view, deepCopy(navContext), deepCopy(tempViewParams));
	} else if (Object.is(view.openMode, 'POPOVER')) {
		openPopOver(view, deepCopy(navContext), deepCopy(tempViewParams));
	} else if (Object.is(view.openMode, 'DRAWER')) {
		openDrawer(view, deepCopy(navContext), deepCopy(tempViewParams));
	}
};

//气泡卡片模式打开视图
const openPopOver = (view: IViewDetail, context: IContext, params: IParam) => {
	App.getOpenViewHelper()
		.openPopover(view, context, params)
		.then((response: any) => {
			if (response.ok) {
				doEditorEmit(response.data);
			}
		});
};
//抽屉模式打开视图
const openDrawer = (view: IViewDetail, context: IContext, params: IParam) => {
	App.getOpenViewHelper()
		.openRightDrawer(view, context, params)
		.then((response: any) => {
			if (response.ok) {
				doEditorEmit(response.data);
			}
		});
};
//模态模式打开视图
const openPopupModal = (
	view: IViewDetail,
	context: IContext,
	params: IParam
) => {
	App.getOpenViewHelper()
		.openModal(view, props.context, params)
		.then((response: any) => {
			if (response.ok) {
				doEditorEmit(response.data);
			}
		});
};

/**
 * @description 处理对象类型参数
 * @param select 选中数据
 */
const handleObjectParams = (select: IParam): IParam => {
	const object: IParam = {};
	if (objectNameField) {
		Object.assign(object, {
			[objectNameField]: select[props.deMajorField],
		});
	}
	if (objectIdField) {
		Object.assign(object, {
			[objectIdField]: select[props.deKeyField],
		});
	}
	if (objectValueField) {
		Object.assign(object, {
			[objectValueField]: deepCopy(select),
		});
	}
	return object;
};

//清空数据
const clear = () => {
	emit('component-action', {
		name: `${props.name}`,
		action: 'valueChange',
		data: null,
	});
	if (props.valueItem) {
		emit('component-action', {
			name: `${props.valueItem}`,
			action: 'valueChange',
			data: null,
		});
	}
};

// 选择值改变(多选删除时调用)
const onChange = (select: string[], dateString: any) => {
	let selects = select.map((item: string) => {
		return items.value.find((_item: any) => {
			return Object.is(item, _item[props.deKeyField]);
		});
	});
	doEditorEmit(selects);
};

const handleViewAction = (name: string, action: any, data: IParam[]) => {
	if (action == 'viewDataChange') {
		doEditorEmit([...data]);
	} else if (action == 'viewClose') {
		open.value = false;
	}
};

// 编辑器抛值
const doEditorEmit = (data: IParam[]): any => {
	let value: any = null;
	let valueItem: any = null;
	if (props.multiple) {
		let selects: any[] = [];
		const _valueItem: string[] = [];
		data.forEach((item: any, i: number) => {
			const index = items.value.findIndex((_item: any) =>
				Object.is(item[props.deKeyField], _item[props.deKeyField])
			);
			if (index < 0) {
				items.value.push(item);
			} else {
				items.value.splice(index, 1, item);
			}
			let selected: any = item[props.deMajorField];
			if (valueType == 'OBJECTS') {
				selected = handleObjectParams(item);
			}
			selects.push(selected);
			_valueItem.push(item[props.deKeyField]);
		});
		if (_valueItem.length > 0) {
			valueItem = _valueItem.join(valueSeparator ? valueSeparator : ',');
		}
		if (selects.length > 0) {
			value =
				valueType == 'OBJECTS' || valueType == 'SIMPLES'
					? selects
					: selects.join(textSeparator ? textSeparator : ',');
		}
	} else {
		const item = data[0];
		if (item) {
			if (valueType == 'OBJECT') {
				value = handleObjectParams(item);
			} else {
				value = item[props.deMajorField];
			}
			valueItem = item[props.deKeyField];
		}
	}
	if (props.valueItem) {
		emit('component-action', {
			name: props.valueItem,
			action: 'valueChange',
			data: valueItem,
		});
	}
	emit('component-action', {
		name: `${props.name}`,
		action: 'valueChange',
		data: value,
	});
};
</script>
